#!/bin/sh
. /etc/functions.sh

ifname=""
real_ifname=$(nvram get wl0_ifname)
real_ifname=${real_ifname:-eth1}
brctl show 2>&- | grep "${real_ifname}" >&- 2>&- && ifname=br0

start_nas() {
	# don't start a new nas process if the old one still lives
	pid="$(cat /var/run/nas.lan.pid 2>&-)"
	[ -n "$pid" -a -d "/proc/$pid" ] && exit 0

	# reduce the probability of a race condition which causes two nas processes to be started
	echo $$ > /var/run/nas.lan.pid                                                  
	sleep 1                                                                         
	[ "$$" = "$(cat /var/run/nas.lan.pid)" ] || exit                                

	echo /usr/sbin/nas $@ > /var/run/nas.lan.conf
	killall -w nas 2> /dev/null > /dev/null
	
	# make sure the interface is up before running nas
	ifconfig "$real_ifname" up

	/usr/sbin/nas "$@" &
	exit
}

auth_mode=$(nvram get wl0_akm)
auth_mode=${auth_mode:-$(nvram get wl0_auth_mode)}
case "$auth_mode" in 
	"wpa")
		auth=2
		mode=wpa
	;;
	"wpa wpa2")
		auth=66
		mode=wpa
	;;
	"wpa2")
		auth=64
		mode=wpa
	;;
	"psk")
		auth=4
		mode=psk
	;;
	"psk psk2")
		auth=132
		mode=psk
	;;
	"psk2")
		auth=128
		mode=psk
	;;	
	*)
		auth=""
	;;
esac

crypto=$(nvram get wl0_crypto)
case "$crypto" in
	tkip)
		crypto_num=2
	;;
	aes)
		crypto_num=4
	;;
	tkip+aes)
		crypto_num=6
	;;
	aes+tkip)
		crypto_num=6
	;;
	*)
		auth=""
  	;;
esac

[ -z "$auth" ] && start_nas -P /var/run/nas.lan.pid ${ifname:+ -l ${ifname}} -H 34954 -i ${real_ifname:?} 2>/dev/null >/dev/null

wl_mode=$(nvram get wl0_mode)
case "${wl_mode}" in
	wet|sta) 
		# nas does not work for bridged client mode. built-in supplicant will handle wpa1
		[ "$ifname" = "br0" ] && exit
		nas_auth="-S "
	;;
	ap) nas_auth="-A ";;
	*) exit 0;;
esac

ssid=$(nvram get wl0_ssid)
ssid=${ssid:-OpenWrt}
gtk_rekey=$(nvram get wl0_wpa_gtk_rekey)
gtk_rekey=${gtk_rekey#0}
gtk_rekey=${gtk_rekey:-3600}

case "$mode" in
	psk)
		psk=$(nvram get wl0_wpa_psk)
		[ -z "$(nvram get wl0_wds)" ] || {
			# nas needs some time before it can accept wds connections
			touch /tmp/.nas_wait
			(
				sleep 10
				rm -f /tmp/.nas_wait
			) &
		}
		start_nas -P /var/run/nas.lan.pid ${ifname:+ -l ${ifname}} -H 34954 -i ${real_ifname:?} ${nas_auth:?} -m ${auth:?} -k "${psk:?}" -s "${ssid:?}" -w ${crypto_num:?} -g ${gtk_rekey:?}
	;;
	wpa)
		key=$(nvram get wl0_radius_key)
		ip=$(nvram get wl0_radius_ipaddr)
		port=$(nvram get wl0_radius_port)
		port=${port:-1812}
		start_nas -P /var/run/nas.lan.pid ${ifname:+ -l ${ifname}} -H 34954 -i ${real_ifname:?} -A -m ${auth:?} -r "${key:?}" -h ${ip:?} -p ${port:?} -t 36000 -s "${ssid:?}" -w ${crypto_num:?} -g ${gtk_rekey:?}
	;;
	*)
		exit 0
	;;
esac


